local class = require 'hump.class'
local HC = require 'hardoncollider'
require 'ship'
require 'laser'
require 'spacephysics'
require 'planet'

function onCollision(dt, a, b)
  if a.parent ~= nil then
    a.parent:onCollide()
  end
  if b.parent ~= nil then
    b.parent:onCollide()
  end
end

Game = class{
  function(self)
    self.w = love.graphics.getWidth()
    self.h = love.graphics.getHeight()
    self.background = love.graphics.newImage('images/background.png')
  
    self.collider = HC(100, onCollision)
    self.borderTop = self.collider:addRectangle(0, -100, self.w, 100)
    self.borderBottom = self.collider:addRectangle(0, self.h, self.w, 100)
    self.borderLeft = self.collider:addRectangle(-100, 0, 100, self.h)
    self.borderRight = self.collider:addRectangle(self.w, 0, 100, self.h)
    self.collider:setPassive(self.borderTop, self.borderBottom, self.borderLeft, self.borderRight)
  
    self.spacephysics = SpacePhysics()
  
    self.planets = {}
    self:newPlanet()
  
    self.ship = Ship('images/redrocket.png', self.w/2, self.h/2, self.collider, self.spacephysics)
    self.gameover = false
  end
}

function Game:newPlanet()
  self.planets[#self.planets+1] = Planet('images/planet.png', self.w/3, 3*self.h/4, self.h/8, 1000000, self.collider, self.spacephysics)
end

function Game:update(dt)
  if self.ship:alive() then
    if love.keyboard.isDown('right') then
      self.ship:rotate(math.pi, dt)
    elseif love.keyboard.isDown('left') then
      self.ship:rotate(-math.pi, dt)
    end
  
    if love.keyboard.isDown('up') then
      self.ship:accelerate(dt)
    end
  
    if love.keyboard.isDown(' ') then
      self.ship:shoot(dt)
    end
  
    self.ship:update(dt)
    self.collider:update(dt)
    self.spacephysics:update(dt)
  elseif love.keyboard.isDown('return') then
    self.gameover = true
  end
end

function Game:running()
  return not self.gameover
end

function Game:draw()
  love.graphics.draw(self.background)
  
  for i = 1,#self.planets do
    self.planets[i]:draw()
  end
  
  self.ship:draw()
  if self.ship:alive() == false then
    love.graphics.printf('Game over. Press enter to exit...', 0, 0, self.w, 'center')
  end
end
